package cn.gailvlun.gll.presentation.emotion.photo

import android.Manifest
import android.app.Dialog
import android.databinding.DataBindingUtil
import android.graphics.Bitmap
import android.graphics.PointF
import android.os.Build
import android.os.Bundle
import android.support.annotation.NonNull
import android.support.v4.view.ViewCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.gailvlun.gll.R
import cn.gailvlun.gll.databinding.FragmentGalleryBinding
import cn.gailvlun.gll.presentation.base.BaseFragment
import cn.gailvlun.gll.util.*
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.davemorrissey.labs.subscaleview.ImageSource
import com.davemorrissey.labs.subscaleview.ImageViewState
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import com.tbruyelle.rxpermissions2.RxPermissions


const val ARG_REAL_PHOTO_URI = "arg_real_photo_uri"
const val ARG_THUMBNAIL_PHOTO_URI = "arg_thumbnail_photo_uri"
const val ARG_BASE_PHOTO_URI = "arg_base_photo_uri"
const val ARG_START_POSITION = "arg_start_position"
const val VIEW_NAME_IMAGE = "image"

class GalleryFragment : BaseFragment() {
    companion object {
        fun newInstance(@NonNull thumbnailPhotoUri: String, @NonNull realPhotoUri: String, @NonNull position: Int): GalleryFragment {
            val bundle = Bundle()
            bundle.putString(ARG_REAL_PHOTO_URI, realPhotoUri)
            bundle.putString(ARG_THUMBNAIL_PHOTO_URI, thumbnailPhotoUri)
            bundle.putInt(ARG_START_POSITION, position)
            val fragment = GalleryFragment()
            fragment.arguments = bundle
            return fragment
        }


        fun newInstance(@NonNull basePhotoUri: String, @NonNull position: Int): GalleryFragment {
            val bundle = Bundle()
            bundle.putString(ARG_BASE_PHOTO_URI, basePhotoUri)
            bundle.putInt(ARG_START_POSITION, position)
            val fragment = GalleryFragment()
            fragment.arguments = bundle
            return fragment
        }
    }

    private lateinit var mBinding: FragmentGalleryBinding
    private lateinit var mRealPhotoUri: String
    private lateinit var mThumbnailPhotoUri: String
    private lateinit var mBasePhotoUri: String
    private var mStartPosition: Int = 0
    private lateinit var mFileName: String
    private var mBitmap: Bitmap? = null
    override fun initComponent(inflater: LayoutInflater, container: ViewGroup?): View {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_gallery, container, false)
        mBinding.presenter=Presenter()
        ViewCompat.setTransitionName(mBinding.ssivImage, "$VIEW_NAME_IMAGE-$mStartPosition")

        return mBinding.root
    }

    override fun createHandler() {
    }

    override fun loadData(savedInstanceState: Bundle?) {
        if (!IsEmpty.string(arguments.getString(ARG_REAL_PHOTO_URI))) {
            mRealPhotoUri = arguments.getString(ARG_REAL_PHOTO_URI)
            mFileName = StringUtil.getFileNameByUrl(mRealPhotoUri)
        }
        if (!IsEmpty.string(arguments.getString(ARG_THUMBNAIL_PHOTO_URI))) {
            mThumbnailPhotoUri = arguments.getString(ARG_THUMBNAIL_PHOTO_URI)
        }

        if (!IsEmpty.string(arguments.getString(ARG_BASE_PHOTO_URI))) {
            mBasePhotoUri = arguments.getString(ARG_BASE_PHOTO_URI)
            mFileName = StringUtil.getFileNameByUrl(mBasePhotoUri)
        }
        mStartPosition = arguments.getInt(ARG_START_POSITION)

        if (isSupportTransitionListener()) {
            loadThumbnail()
        } else {
            loadRealPhoto()
        }
    }


    private fun isSupportTransitionListener(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            activity.window.sharedElementEnterTransition?.addListener(object : android.transition.Transition.TransitionListener {
                override fun onTransitionResume(p0: android.transition.Transition?) {
                }

                override fun onTransitionPause(p0: android.transition.Transition?) {
                }

                override fun onTransitionCancel(p0: android.transition.Transition?) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        p0?.removeListener(this)
                    }
                }

                override fun onTransitionStart(p0: android.transition.Transition?) {
                }

                override fun onTransitionEnd(p0: android.transition.Transition?) {

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        p0?.removeListener(this)
                    }
                }
            })
            return true
        }

        return false

    }

    var pd: Dialog? = null
    private fun loadThumbnail() {

        Glide.with(activity)
                .asBitmap()
                .load(mRealPhotoUri)
                .listener(object : RequestListener<Bitmap> {
                    override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {

                        return false
                    }

                    override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {

                        return false
                    }
                })
                .into(object : SimpleTarget<Bitmap>() {
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        mBitmap = resource
                        val (isSuccessful, file) = FileUtil.saveBitmapToFile(mFileName, resource)
                        if (isSuccessful) {
                            mBinding.ssivImage.setImage(ImageSource.uri(file?.absolutePath), ImageViewState(0.5f, PointF(0f, 0f), 0))

                        }
                    }

                })
    }

    fun loadRealPhoto() {
        Glide.with(activity)
                .asBitmap()
                .load(mRealPhotoUri)
                .listener(object : RequestListener<Bitmap> {
                    override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {

                        return false
                    }

                    override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {

                        return false
                    }
                })
                .into(object : SimpleTarget<Bitmap>() {
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        mBitmap = resource
                        val (isSuccessful, file) = FileUtil.saveBitmapToFile(mFileName, resource)
                        if (isSuccessful) {

                            mBinding.ssivImage.setImage(ImageSource.uri(file?.absolutePath), ImageViewState(0.5f, PointF(0f, 0f), 0))

                        }
                    }

                })
    }

    inner class Presenter {
        fun onClickImage() {
            if (activity != null) {
                activity.onBackPressed()
            }
        }

        fun onLongClickImage(view: View): Boolean {
            if (view is SubsamplingScaleImageView) {
                DialogUtil.showHint(mContext, "是否保存该图片") { dialog, which ->
                    RxPermissions(activity)
                            .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .subscribe { aBoolean ->
                                if (aBoolean!!) {

                                    val (isSuccessful, file) = FileUtil.saveBitmapToFile(FileUtil.IMAGES_DIR,mFileName, mBitmap!!)
                                    if (isSuccessful){
                                        ToastUtil.showShort("保存成功")
                                    }else{
                                        ToastUtil.showShort("保存失败")
                                    }
                                } else {
                                    ToastUtil.showShort("没有权限")
                                }
                            }
                }
                return true
            }
            return false
        }
    }









































}